package com.zyl.blog.controller;/**
 * @author 14323
 * @date 2020/8/7 15:51
 */

import com.zyl.blog.pojo.Blog;
import com.zyl.blog.service.BlogService;
import com.zyl.blog.service.CommentService;
import com.zyl.blog.service.TagService;
import com.zyl.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @Description: TODO
 * @author: scott
 * @date: 2020年08月07日 15:51
 */
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping({"/","/index"})
    public String index(@PageableDefault(size = 7, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                        Model model){

        model.addAttribute("page", blogService.getBlogPage(pageable));
        model.addAttribute("types", typeService.getTopType(6));
        model.addAttribute("tags", tagService.getTopTag(10));
        model.addAttribute("recommendBlogs", blogService.getTopBlog(8));

        return "index";
    }

    @PostMapping("/search")
    public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model){

        model.addAttribute("page", blogService.getSearchBlogPage("%" + query + "%", pageable));
        model.addAttribute("query",query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model){

        model.addAttribute("blog", blogService.getAndConvert(id));
        //评论数据交由前端ajax请求获取
        return "blog";
    }

    @GetMapping("/footer/latestBlogList")
    public String latestBlogList(Model model) {
        Page<Blog> topBlog = blogService.getTopBlog(3);
        System.out.println(topBlog);
        model.addAttribute("latestBlogList", blogService.getTopBlog(3));
        return "_fragments :: latestBlogList";
    }
}
